package com.chenhy.springbootvuesmbms.filter;

import com.chenhy.springbootvuesmbms.security.LoginUser;
import com.chenhy.springbootvuesmbms.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader("token");
        System.out.println(token);

        // 判断请求头中是否有Token
        // 如果token为空
        if (!StringUtils.hasText(token)){
            // 直接放行，不查询数据放入SecurityContext，让过滤链的后续过滤器处理
            filterChain.doFilter(request,response);
            System.out.println("Token为空");
            return;
        }

        // 解析请求头的Token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Token非法");
        }

        // 从Redis中查出用户信息
        String key = "Login:"+userId;
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(key);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        // 将该用户的信息存放到SecurityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);
    }
}
